package com.crm.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class CommonUtil {
	
	/**
	 * 取得当前日期
	 * @param separator 分隔符 -  /  _ 等
	 * @return
	 */
	public static String  getDate(String separator){
		  StringBuffer date=new StringBuffer();
		  Calendar cal=Calendar.getInstance();//使用日历类
		  int year=cal.get(Calendar.YEAR);//得到年
		  int month=cal.get(Calendar.MONTH)+1;//得到月，因为从0开始的，所以要加1
		  int day=cal.get(Calendar.DAY_OF_MONTH);//得到天
		  //int hour=cal.get(Calendar.HOUR);//得到小时
		  //int minute=cal.get(Calendar.MINUTE);//得到分钟
		  //int second=cal.get(Calendar.SECOND);//得到秒
		  //System.out.println("结果："+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second);
		  date.append(year).append(separator).append(month).append(separator).append(day);
		return date.toString();
	}
	
	/**
	 * 取得当前日期包含时分秒
	 * @param separator 分隔符 -  /  _ 等
	 * @return
	 */
	public static String  getDateAll(String separator){
		  /*StringBuffer date=new StringBuffer();
		  Calendar cal=Calendar.getInstance();//使用日历类
		  int year=cal.get(Calendar.YEAR);//得到年
		  int month=cal.get(Calendar.MONTH)+1;//得到月，因为从0开始的，所以要加1
		  int day=cal.get(Calendar.DAY_OF_MONTH);//得到天
		  int hour=cal.get(Calendar.HOUR);//得到小时
		  int minute=cal.get(Calendar.MINUTE);//得到分钟
		  int second=cal.get(Calendar.SECOND);//得到秒
		  //System.out.println("结果："+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second);
		  date.append(year).append(separator).append(month).append(separator).append(day).append(" ").append(hour).append(":").append(minute).append(":").append(second);
		return date.toString();*/
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return  sdf.format(new Date());
	}
	
	public static String getCurrentDate() {
		Date dNow = new Date();   //当前时间
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
		return sdf.format(dNow);    //格式化前一天
	}
	
	public static String getBeforeData(){
		Date dNow = new Date();   //当前时间
		Date dBefore = new Date();
		Calendar calendar = Calendar.getInstance();  //得到日历
		calendar.setTime(dNow);//把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
		dBefore = calendar.getTime();   //得到前一天的时间
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
		return sdf.format(dBefore)+" 00:00:00";    //格式化前一天
	}
	
    /**
     * 产生唯一文件名，包括缩略图文件名以T字母开头
     * @return 文件名及缩略图文件名
     */
    public static String[] getNewFileName(){	
    	String fileNames[] =new String[3];
        Random random = new Random();
		int add = random.nextInt(10000000); // 产生随机数10000000以内
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String  ti= sdf.format(new Date());
		String ret = add +ti;
		fileNames[0]=ret;
		fileNames[1]="M"+ret;
		fileNames[2]="T"+ret;
		return fileNames;
    }
	/**
	 * 验证文件是否允许上传
	 * 首先检查文件后缀是否有效，通过之后则检查文件编码是否正确
	 *
	 * @param file 文件
	 * @param types 允许上传的文件类型
	 * @param fileExt 文件后缀
	 * @return  map.get(0)= true or false ;map.get(1)= 文件大小
	 */
	public static Map<Integer,Object> validateImgFile(File file,String types[] ,String fileExt){
		//默认判断结果为false
		boolean result = false;
		double size = 0;
		for(String type:types){
			//判断后缀名是否允许上传
			if(type.equals(fileExt)){
				//判断文件编码是否正确
				result = validateTypeHead(file);
				//如果正确则判断文件大小是否超过限制
				if(result){
					FileInputStream  fileIS=null;
					try{
						//取得文件流
						fileIS = new FileInputStream(file);
						//取得文件大小
						size = fileIS.available();
						size = Math.round(size/1024*100)*.01;
						//当文件小于2000kb时允许上传 否则不允许
						if(size > 0 && size<2000){
							result = true;
						}else{
							size = 0;
							result = false;
						}
					}catch(Exception e){
						result =false;
					}finally{
						if(fileIS !=null){
							try{
								fileIS.close();
							}catch(Exception e){}
						}
					}
				}
				break;
			}
		}
		Map<Integer,Object> resultMap = new HashMap<Integer,Object>();
		resultMap.put(0, result);
		resultMap.put(1, size);
		return resultMap;
	}
	
	public static boolean validateFileType(String type){
		boolean result = false;
    	try{
    		Resource resource = new ClassPathResource("/resource.properties");
	    	Properties props = PropertiesLoaderUtils.loadProperties(resource);
	    	String types =(String)props.get("fileTypes");
	    	String[] typesStr = types.split("\\|");
	    	for(String typeStr :typesStr){
	    		if(typeStr.equals(type)){
	    			result = true;
	    			break;
	    		}
	    	}
    	}catch(Exception e){
    	}
    	 return result;
    	
	}
	
	public static boolean validateImgType(String type){
		boolean result = false;
    	try{
    		Resource resource = new ClassPathResource("/resource.properties");
	    	Properties props = PropertiesLoaderUtils.loadProperties(resource);
	    	String types =(String)props.get("imgFileTypes");
	    	String[] typesStr = types.split("\\|");
	    	for(String typeStr :typesStr){
	    		if(typeStr.equals(type)){
	    			result = true;
	    			break;
	    		}
	    	}
    	}catch(Exception e){
    	}
    	 return result;
    	
	}
	
	/**
	 * 检查文件头(检查文件编码)
	 * @param file
	 * @return
	 */
	public static boolean validateTypeHead(File file) {   
        if (file == null) {   
            return false;   
        }   
        try {   
            byte[] imgContent = FileUtils.readFileToByteArray(file);   
            int len = imgContent.length;   
            byte n1 = imgContent[len - 2];   
            byte n2 = imgContent[len - 1];   
            byte b0 = imgContent[0];   
            byte b1 = imgContent[1];   
            byte b2 = imgContent[2];   
            byte b3 = imgContent[3];   
            byte b4 = imgContent[4];   
            byte b5 = imgContent[5];   
            byte b6 = imgContent[6];   
            byte b7 = imgContent[7];   
            byte b8 = imgContent[8];   
            byte b9 = imgContent[9];   
               
            //GIF(G I F 8 7 a)   
            if (b0 == (byte)'G' && b1 == (byte)'I' && b2 == (byte)'F' && b3 == (byte)'8' && b4 == (byte)'7' && b5 == (byte)'a') {   
                return true;   
            //GIF(G I F 8 9 a)   
            } else if (b0 == (byte)'G' && b1 == (byte)'I' && b2 == (byte)'F' && b3 == (byte)'8' && b4 == (byte)'9' && b5 == (byte)'a') {   
                return true;   
            //PNG(89 P N G 0D 0A 1A)   
            }else if (b0 == -119 && b1 == (byte)'P' && b2 == (byte)'N' && b3 == (byte)'G' && b4 == 13 && b5 == 10 && b6 == 26) {   
                return true;   
            //JPG JPEG(FF D8 --- FF D9)   
            } else if (b0 == -1 && b1 == -40 && n1 == -1 && n2 == -39){   
                return true;   
            } else if (b6 == (byte)'J' && b7 == (byte)'F' && b8 == (byte)'I' && b9 == (byte)'F'){   
                return true;   
            } else if (b6 == (byte)'E' && b7 == (byte)'x' && b8 == (byte)'i' && b9 == (byte)'f'){   
                return true;   
            //BMP(B M)   
            } else if (b0 == (byte)'B' && b1 == (byte)'M') {   
                return true;   
            }else {   
                return false;   
            }   
        } catch (ArrayIndexOutOfBoundsException e) {   
            return false;   
        } catch (IOException e) {   
            return false;   
        }   
    }  
	
	/**
	 * 取得文件名及文件后缀名 [0]为文件名  [1]为文件后缀
	 * @param fileName
	 * @return
	 */
	public static String[] splitFileName(String fileName){
		String fileAndExt[] ={fileName.substring(0,fileName.lastIndexOf(".")),
				fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase()};
		return fileAndExt;
	}
	
	/**
     * 根据传入的市的value获取省的value
     * 
     * */
    public static String getProvinceValue(String cityValue){
    	/*省，市之间的value关系：XX 00 省 XX xx 市,只要将传入的市的值的后两位替换成00就行了*/
    	/*substring(0, 2) 返回的是一个string字符串 重第0个字符开始 截两位 */
    	StringBuffer sb = new StringBuffer(cityValue.substring(0, 2));
    	sb.append("00");
    	return sb.toString();
    }
	
    /**
     * 查看字段里面包含手机或电话号码的有多少个   用户复制内容监听
     * @param string
     * @return
     */
    public static int findPhoneCount(String string) {
    	int i = 0;
    	try{
    		   Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[34578]\\d{9})|(?:861[34578]\\d{9})|(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?))(?!\\d)");
    	        Matcher matcher = pattern.matcher(string);
    	       // StringBuffer bf = new StringBuffer(64);
    	        
    	        while (matcher.find()) {
    	          //bf.append(matcher.group()).append(",");
    	          //  string = string.replace(matcher.group(), matcher.group().substring(0,3)+"********");
    	            i++;
    	        } 
    	}catch(Exception e){
    		
    	}
        return i;
    }
    
    /**
     * 隐藏号码
     * @param string
     * @return
     */
    public static String hidPhone(String string) {
    	try{
    		   Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[34578]\\d{9})|(?:861[34578]\\d{9})|(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?))(?!\\d)");
    	        Matcher matcher = pattern.matcher(string);
    	        StringBuffer bf = new StringBuffer();
    	        while (matcher.find()) {
    	        	  string = string.replace(matcher.group(), matcher.group().substring(0,3)+"****"+ matcher.group().substring(matcher.group().length()-3,matcher.group().length()));
    	        } 
    	}catch(Exception e){
    		
    	}
        return string;
    }
    
    /** 
     * 从网络Url中下载文件 
     * @param urlStr 
     * @param fileName 
     * @param savePath 
     * @throws IOException 
     */  
    public static File  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
                //设置超时间为3秒  
        conn.setConnectTimeout(30*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  
        //得到输入流  
        InputStream inputStream = conn.getInputStream();    
        //获取自己数组  
        byte[] getData = readInputStream(inputStream);      
  
        //文件保存位置  
        File saveDir = new File(savePath);  
        if(!saveDir.exists()){  
            saveDir.mkdir();  
        }  
        File file = new File(saveDir+File.separator+fileName);      
        FileOutputStream fos = new FileOutputStream(file);       
        fos.write(getData);   
        if(fos!=null){  
            fos.close();    
        }  
        if(inputStream!=null){  
            inputStream.close();  
        }  
   
        return file;
     //   System.out.println("info:"+url+" download success");   
  
    }  
  
  
  
    /** 
     * 从输入流中获取字节数组 
     * @param inputStream 
     * @return 
     * @throws IOException 
     */  
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
        byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    
        while((len = inputStream.read(buffer)) != -1) {    
            bos.write(buffer, 0, len);    
        }    
        bos.close();    
        return bos.toByteArray();    
    }    
    
    
    public static int getAudioTime(File file) {
    	int times =1;
    	  try {  
        	  Clip clip = AudioSystem.getClip();
              AudioInputStream ais = AudioSystem.getAudioInputStream(file);
              clip.open(ais);
              Double time= clip.getMicrosecondLength() / 1000000D;
              return time.intValue();
          } catch(Exception e) {  
              e.printStackTrace();  
          }  
    	  return times;
    }
  
    public static void main(String[] args) {  
        try{  
            downLoadFromUrl("http://cloudcallcenter-online.oss-cn-shanghai.aliyuncs.com/record/d0920c2d-804d-4959-b45b-8341006cdf2a/152721158314400080310502.wav?Expires=1527326778&OSSAccessKeyId=LTAIvKWEr4DoFSqz&Signature=GosjafbGD%2Fw0%2FUP8vm9zLC7mn4s%3D",  
                    "152721158314400080310502.wav","d:/uc/");  
        }catch (Exception e) {  
            // TODO: handle exception  
        	e.printStackTrace();
        }  
    } 
    
}
